import { app, BrowserWindow, Menu } from 'electron'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { createIpcHandlers } from './preload/ipc-handlers'
import { appTitle } from './config'

const __dirname = dirname(fileURLToPath(import.meta.url))

/**
 * 创建主窗口
 */
function createMainWindow() {
  const mainWindow = new BrowserWindow({
    title: appTitle,
    width: 800,
    height: 600,
    webPreferences: {
      preload: join(__dirname, './preload.mjs'),
      nodeIntegration: false,
      contextIsolation: true,
    },
  })

  // 加载页面内容
  if (process.env.VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
  } else {
    mainWindow.loadFile('dist-web/index.html')
  }

  if (process.env.NODE_ENV === 'development') {
    process.on('message', msg => {
      if (msg === 'electron-vite&type=hot-reload') {
        for (const win of BrowserWindow.getAllWindows()) {
          // Hot reload preload scripts
          win.webContents.reload()
        }
      }
    })
  }

  Menu.setApplicationMenu(null)

  return mainWindow
}

app.whenReady().then(() => {
  const mainWindow = createMainWindow()
  createIpcHandlers(mainWindow)
  mainWindow.webContents.openDevTools({ mode: 'bottom' })

  // 当应用被激活时创建主窗口
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createMainWindow()
    }
  })
})

// 所有窗口都关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
